<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>vue-elementui upload组件的上传文件控制 | haijd</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="Vue" />
  
  
  
  
  <meta name="description" content="Vue-ElementUI upload组件的上传文件控制，上传失败文件的复原，作为表单时的填充">
<meta name="keywords" content="Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue-ElementUI upload组件的上传文件控制">
<meta property="og:url" content="http://www.hais2.com/2018/06/14/Vue-ElementUI-upload-file-controller/index.html">
<meta property="og:site_name" content="haijd">
<meta property="og:description" content="Vue-ElementUI upload组件的上传文件控制，上传失败文件的复原，作为表单时的填充">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://cdn-images-1.medium.com/max/1003/1*M20GkaLW-OBcz6-ifDAJEg.png">
<meta property="og:updated_time" content="2018-06-14T02:38:49.517Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Vue-ElementUI upload组件的上传文件控制">
<meta name="twitter:description" content="Vue-ElementUI upload组件的上传文件控制，上传失败文件的复原，作为表单时的填充">
<meta name="twitter:image" content="https://cdn-images-1.medium.com/max/1003/1*M20GkaLW-OBcz6-ifDAJEg.png">
  
    <link rel="alternate" href="/atom.xml" title="haijd" type="application/atom+xml">
  
  <link rel="icon" href="/css/images/favicon.ico">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
    
  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1" type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >
  <link rel="stylesheet" href="/css/hiero.css" >
  <link rel="stylesheet" href="/css/glyphs.css" >
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>

<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="haijd" rel="home"> haijd </a>
            
          </h1>

          
            <div class="site-description">Stay Hungry,Stay Foolish</div>
          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Vue-ElementUI-upload-file-controller" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
<div class="article-gallery">
  <div class="article-gallery-photos">
    
      <a class="article-gallery-img fancybox" href="https://cdn-images-1.medium.com/max/1003/1*M20GkaLW-OBcz6-ifDAJEg.png" rel="gallery_cjie4nal000753swafyltfkau">
        <img src="https://cdn-images-1.medium.com/max/1003/1*M20GkaLW-OBcz6-ifDAJEg.png" itemprop="image">
      </a>
    
  </div>
</div>

    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      Vue-ElementUI upload组件的上传文件控制
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/2018/06/14/Vue-ElementUI-upload-file-controller/" class="article-date">
	  <time datetime="2018-06-14T02:06:13.000Z" itemprop="datePublished">June 14, 2018</time>
	</a>

      
	<span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <!-- TOC -->
<ul>
<li><a href="#1-上传失败文件恢复">1. 上传失败文件恢复</a></li>
<li><a href="#2-复原文件上传成功表单">2. 复原文件上传成功表单</a></li>
</ul>
<!-- /TOC -->
<h1 id="1-上传失败文件恢复"><a href="#1-上传失败文件恢复" class="headerlink" title="1. 上传失败文件恢复"></a>1. 上传失败文件恢复</h1><p>element的上传组件有很多需要自行控制的东西，此次遇到的问题是怎么在上传失败后，保持选择的文件的不变，可以再次尝试上传。</p>
<p>首先我们有一个事件，是上传失败后的回调事件：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 文件上传失败后的事件</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  uploadErrorFunc(err, file, fileList)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(file)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>这个事件会在每个文件上传失败后都进行调用，我们需要保持选择文件的不变，需要在这里做文章。<br>在分析之前，我们先看看选择的文件有什么值得注意的数据，这里我们还需要写一个文件选择(改变的事件)：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 文件列表改变事件</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  onChange(file, fileList) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(file)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></p>
<p>这个function会在选择每个文件的时候都触发一次，我们打印一下选择的文件信息看看有什么数据：<br><img src="/image/Frontend/2018-6-14-1.jpg" alt=""><br>比较重要的就是红框中标出的数据，都是文件的信息。</p>
<p>然后我们让文件上传失败，看看失败后回传的文件信息有哪些数据：<br><img src="/image/Frontend/2018-6-14-2.jpg" alt=""></p>
<p>在上面两组数据中，我们需要注意的是<code>status</code>这个属性，可以看到，选择文件的时候值为<code>ready</code>，文件上传失败后回传的文件的值为<code>fail</code>，同一个文件有两种状态，我们这时候就大概能知道UI组件的处理方式了。</p>
<p>我们把错误回调事件中拿到的file的status属性的值改为”ready”就可以了。</p>
<p>接下来，我们把this.$refs.upload打印出来：<br><img src="/image/Frontend/2018-6-14-3.jpg" alt=""><br>数据很多，我们关注一个主要的属性，uploadFiles，从名字就可看出来，这是需要上传的文件的列表数据，很容易就想到处理的办法了，在错误发生时，拿到回调的file数据，并且把file中的status属性的值改为预备状态”ready”，然后push到upload组件的uploadFiles数组中。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 文件上传失败后的事件</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> uploadErrorFunc(err, file, fileList)&#123;</span><br><span class="line">     file.status=<span class="string">"ready"</span></span><br><span class="line">     <span class="keyword">this</span>.$refs.upload.uploadFiles.push(file);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="2-复原文件上传成功表单"><a href="#2-复原文件上传成功表单" class="headerlink" title="2. 复原文件上传成功表单"></a>2. 复原文件上传成功表单</h1><p>有时候我们的上传组件在一个form表单中，在更新表单的时候，我们需要让上次上传的图片恢复成上传成功的样子，那么也可以使用上面的方式进行编写。</p>
<p>也就是更新表单的时候，让上传过的图片出现在上传组件中，同样是给<code>this.$refs.upload.uploadFiles</code>赋值，只不过这时的<code>status</code>变成了<code>success</code>。需要注意的是，这时的url需要是一个可以外网访问到的图片，也就是图片的完整链接。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">this</span>.$refs.upload.uploadFiles=[&#123;</span><br><span class="line">    status:<span class="string">"success"</span>,</span><br><span class="line">    url:imgUrl  <span class="comment">//赋值返回的图片完整链接</span></span><br><span class="line">&#125;]</span><br></pre></td></tr></table></figure></p>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/Frontend/">Frontend</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Vue/">Vue</a></li></ul>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: 'Donate', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: '/css/images/wechatPay.png',
  alipayImage: '/css/images/alipay.jpg'
});
</script>
      

      
        
	<section id="comments" class="comment">
	  <div id="disqus_thread">
	  <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
	  </div>
	</section>

	<script type="text/javascript">
	var disqus_shortname = 'haijdblog';
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/count.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	</script>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2018/06/14/Spring-Boot-Annotations-1/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          Spring Boot Annotations
        
      </div>
    </a>
  
  
    <a href="/2018/06/13/Spring-Web-Annotations-1/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Spring Web Annotations</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-上传失败文件恢复"><span class="nav-number">1.</span> <span class="nav-text">1. 上传失败文件恢复</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-复原文件上传成功表单"><span class="nav-number">2.</span> <span class="nav-text">2. 复原文件上传成功表单</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

  <div class="clearfix container">
      <div class="site-info">
	      &copy; 2018 haijd All Rights Reserved.
          
            <span id="busuanzi_container_site_uv">
              本站访客数<span id="busuanzi_value_site_uv"></span>人次  
              本站总访问量<span id="busuanzi_value_site_pv"></span>次
            </span>
          
      </div>
      <div class="site-credit">
        Theme by <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
      </div>
  </div>
</footer>


<!-- min height -->

<script>
    var contentdiv = document.getElementById("content");

    contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>








	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
